package com.situ.shoplook.admin.service.impl;


import com.situ.shoplook.admin.service.UpLoadFileService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author:yzy
 * @date:2024/8/12
 */
@Service
@Primary
public class UploadFileServiceImpl implements UpLoadFileService {
    //文件上传路径
    @Value("${upload.location}")
    private String uploadFileLocation;
    //文件访问前缀
    @Value("${upload.server.prefix}")
    private String uploadServerPrefix;
    /**
     * @param file 头像文件
     * @return 访问路径
     */
    @Override
    public String uploadAvatar(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("Uploaded file cannot be null or empty");
        }

        // 获取上传的文件的原文件名
        String fileName = file.getOriginalFilename();
        int dotIndex = fileName.lastIndexOf(".");
        // 取得扩展名
        String ext = fileName.substring(dotIndex);

        // 生成一个新的文件名，以时间命名
        fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 完整的文件名
        fileName += ext;

        File dir = new File(uploadFileLocation + "/images/avatar/");
        if (!dir.exists()) {
            dir.mkdirs(); // 手动显式递归创建目录
        }

        try {
            // 目标文件
            File dest = new File(dir.getCanonicalPath() + "/" + fileName);
            // 将整个文件传输到目标文件
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        System.out.println(fileName);

        return uploadServerPrefix + "images/avatar/" + fileName;
    }

    @Override
    public String uploadImage(MultipartFile file, String type) {
        String fileName = file.getOriginalFilename();//上传文件名
        int idx = fileName.lastIndexOf(".");
        String ext = fileName.substring(idx);//扩展名
        fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        fileName += ext;

        File dest = new File(uploadFileLocation + "/images/" + type + "/");
        if (!dest.exists()) {
            dest.mkdirs();
        }

        try {
            dest = new File(dest.getCanonicalPath() + "/" + fileName);
            file.transferTo(dest);//传输文件

            return uploadServerPrefix + "images/" + type + "/" + fileName;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

